<template>
  <div class="position-relative">
    <HyInput
      @focus="hasTreeselect = true"
      v-model="treeselectName"
      class="position-relative"
      :placeholder="placeholder"
      :disabled="disabled"
    >
      <template #suffix>
        <i
          v-if="!disabled && treeselectName"
          @click="clearHandler()"
          class="el-icon-close clear-icon"
        ></i>
        <i
          v-if="!disabled"
          class="treeselect-icon"
          :class="[
            hasTreeselect ? 'el-icon-caret-top' : 'el-icon-caret-bottom',
          ]"
          @click="hasTreeselect = !hasTreeselect"
        ></i>
      </template>
    </HyInput>
    <HyTree
      v-if="hasTreeselect"
      class="treeselect position-absolute"
      :data="list"
      empty-text="暂无数据"
      :highlight-current="true"
      @node-click="nodeClick"
      :expand-on-click-node="false"
    >
    </HyTree>
  </div>
</template>

<script>
import { ElInput, ElTree } from 'element-plus';
import { reactive, toRefs } from 'vue';
import { deepCopy } from '@/utils/tools';
export default {
	components : {
		HyInput : ElInput,
		HyTree : ElTree
	},
	props : {
		/**
     * v-model
     * 默认子父组件，同步更新默认modelValue
     * 如：父组件v-model:pid 这里props应该改成pid
     * 通过 emit update:xx 触发更新
     */
		modelValue : {
			type : [String, Number]
		},
		disabled : {
			type : Boolean,
			default : false
		},
		defaultValue : {
			type : [String, Number],
			default : '请选择'
		},
		placeholder : {
			type : String,
			default : '请选择'
		},
		treeselectList : {
			type : Array,
			required : true
		},
		dataAdaptiveMap : {
			type : Object,
			default : () => ({
				id : 'id',
				label : 'label'
			})
		}
	},
	setup (prop, context) {
		let state = reactive({
			list : [],
			treeselectName : '',
			treeselectId : '',
			hasTreeselect : false
		});
		let nodeClick = (params) => {
			state.treeselectName = params.label;
			state.treeselectId = params.id;
			context.emit('update:modelValue', params.id);
			state.hasTreeselect = false;
		};

		/**
     *  数据转换
     */
		let dataAdaptive = (list, treeselectMap = {}) => {
			list.forEach((item) => {
				Object.keys(item).forEach((key) => {
					// 需要转换的key
					if (prop.dataAdaptiveMap[key]) {
						item[prop.dataAdaptiveMap[key]] = item[key];
						delete item[key];
					}

					if (item.id) {
						let tempMap = deepCopy(item);
						if (tempMap.children) {
							delete tempMap.children;
						} else if (Array.isArray(tempMap[key])) {
							delete tempMap[key];
						}
						treeselectMap[item.id] = tempMap;
					}

					// 默认children是子节点
					if (item.children && item.children.length > 0) {
						dataAdaptive(item.children, treeselectMap);
					} else if (Array.isArray(item[key]) && item[key].length > 0) {
						dataAdaptive(item[key], treeselectMap);
					}
				});
			});
			return { list, treeselectMap };
		};

		let clearHandler = () => {
			state.treeselectName = '';
			state.treeselectId = '';
			context.emit('update:modelValue', {});
		};
		let init = () => {
			let { list, treeselectMap } = dataAdaptive(deepCopy(prop.treeselectList));
			state.list = list;
			let { id, label } = treeselectMap[prop.modelValue] || {};
			state.treeselectName = label;
			state.treeselectId = id;
		};

		init();

		return {
			clearHandler,
			nodeClick,
			...toRefs(state)
		};
	}
};
</script>

<style lang="scss" scoped>
.treeselect {
  width: 100%;
  background: #ffffff;
  z-index: 9999;
  max-height: 200px;
  border-radius: 0 0 4px 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  overflow-y: scroll;
}
.treeselect-icon {
  cursor: pointer;
  &:hover {
    color: #616161;
  }
}
.clear-icon {
  cursor: pointer;
  font-size: 12px;
  font-weight: bold;
  &:hover {
    color: #e53935;
  }
}
</style>
